<template>
  <el-dialog title="用例列表" :visible.sync="dialogVisibleCase" :before-close="closeTask" top="50px" append-to-body width="90%">
    <div class="flex">
      <div class="left">
        <div class="left-div">
          <el-row>
            <el-col :span="12">
              <span class="title">接口用例</span>
              <i class="el-icon-plus" @click="newly" v-if="type === 2" style="font-size: 16px;cursor: pointer"></i>
            </el-col>
            <el-col :span="12" style="text-align:right" v-if="type === 1">
              <el-button type="primary" size="mini" @click="newly">新增</el-button>
              <el-button type="danger" size="mini" @click="deleteDate">批量删除</el-button>
            </el-col>
            <el-col :span="12" style="text-align:right" v-if="type === 2">
              <!--<el-button type="primary" size="mini" @click="newly">新增</el-button>-->
              <el-button type="primary" size="mini" @click="use">引用</el-button>
              <!--<el-button type="primary" size="mini" @click="add()">添加</el-button>-->
            </el-col>
          </el-row>
          <div class="search">
            <el-input placeholder="请输入内容" size="mini" v-model="searchText" class="input-with-select">
              <el-button slot="append" icon="el-icon-search" @click="onloadeList"></el-button>
            </el-input>
          </div>
          <div class="table">
            <el-table ref="multipleTable" highlight-current-row row-class-name="rowCursor" :data="caseList"
                      @selection-change="handleSelectionChange" @row-click="rowClick">
              <el-table-column type="selection" width="55"></el-table-column>
              <el-table-column label="序号" type="index" width="60"></el-table-column>
              <el-table-column prop="useCaseName" label="用例名" show-overflow-tooltip></el-table-column>
              <el-table-column label="操作" show-overflow-tooltip>
                <template slot-scope="scope">
                  <i class="el-icon-edit caoz" @click.stop="update(scope.row)"></i>
                  <i class="el-icon-delete caoz" @click.stop="oneDelete(scope.row)"></i>
                </template>
              </el-table-column>
            </el-table>
          </div>
          <div class="dialog-footer">
            <el-pagination
              @size-change="handleSizeChange"
              @current-change="handleCurrentChange"
              :current-page="page.pageNum"
              :page-sizes="[10, 20, 30, 40]"
              :page-size="page.pageSize"
              class="page"
              layout="total, sizes, prev, pager, next"
              :total="page.total">
            </el-pagination>
          </div>
        </div>
      </div>
      <div class="right" id="interfaceRight">
        <el-form ref="form" :rules="rules" :model="form" label-width="80px" style="background-color: #f5f5f5;padding: 15px;padding-bottom: 1px;margin-bottom: 30px;">
          <el-form-item label="用例名称" prop="useCaseName">
            <el-input v-model="form.useCaseName" size="mini" :disabled="disabled" placeholder="请输入用例名称" @input="setInput"
                      style="width:300px"></el-input>
          </el-form-item>
          <el-form-item label="备注" prop="noteCaseName">
            <el-input type="textarea" placeholder="请输入备注" :disabled="disabled" v-model="form.remark" :rows="5" @input="setInput"></el-input>
          </el-form-item>
        </el-form>
        <div>
          <InterfaceConfig ref="interfaceConfig" v-if="isNode" :disabled="disabled" :node="node" assert-id="caseAssert" textarea-id="caseTextarea"/>
        </div>
        <div class="footer-btn">
          <el-button type="primary" size="mini" @click="doTest">测试</el-button>
          <el-button v-if="!disabled && !isAdd" type="success" size="mini" @click="add">另存为</el-button>
          <el-button v-if="!disabled" type="primary" size="mini" @click="saveUpdate">保存</el-button>
        </div>
      </div>
    </div>
  </el-dialog>
</template>
<script>
  import InterfaceConfig from '@/rdComponent/common/InterfaceConfig'
  export default {
    name: "CaseList",
    components: {
      InterfaceConfig
    },
    props: {
      dialogVisibleCase: {
        type: Boolean,
        default: false,
        required: true
      },
      node: {
        type: Object,
        default: {},
        required: true
      },
      type: Number,
      historyList: {
        type: Array
      }
    },
    data() {
      return {
        searchText: '',//搜索内容
        caseList: [],//用例列表
        multipleSelection: [],
        page: { //分页
          pageSize: 10,
          pageNum: 1,
          total: 0
        },
        isNode: true,
        form: {//表单数据
          useCaseName: '',
          noteCaseName:'',
          remark: ''
        },
        interfaceName: this.node.siaName,
        seccesstest: true,
        rules: {
          useCaseName: [
            {required: true, message: '请输入用例名称', trigger: 'blur'},
            {max: 20, message: '最多 20 个字符', trigger: 'blur'}
          ],
          noteCaseName:[
            {max: 255, message: '最多255个字符', trigger:'blur'}
          ],
        },
        disabled: false,
        isAdd: false,
        isChange: false
      }
    },
    created() {
      this.onloadeList()
      console.log("node:", this.node);
    },
    methods: {
      /**监听是否输入了**/
      setInput() {
        this.isChange = true;
      },
      //保存
      saveUpdate(){
        let data = this.getData();
        if (this.id) {
          data.id=this.id
          data.assertConditions[0].fkId = this.id;
          this.axios.put('/api/test/use/case/modify',data)
            .then((res)=>{
              if(res.data.status === 0){
                this.onloadeList();
                this.disabled = true;
                this.$message({message: '保存成功',type: 'success'});
                this.isChange = false;
              }
            }).catch((err)=>{
            this.$message({message: '保存失败',type: 'warning'});
          })
        }
        else {
          this.add();
        }
      },
      /**新增**/
      newly() {
        this.isAdd = true;
        this.form = {
          useCaseName: "",
          remark: ""
        }
        this.id = "";
        delete this.node.updateInterfaceJson;
        delete this.node.updateParamsJson;
        delete this.node.updateAssertJson;
        this.isNode = false;
        this.$nextTick(() => {
          this.isNode = true;
          this.disabled = false;
        })

      },
      /**测试**/
      doTest() {
        this.$refs.interfaceConfig.clickTest(this.getData());
      },
      //初始化加载
      onloadeList() {
        let params = {
          pageNum: this.page.pageNum,
          pageSize: this.page.pageSize,
          useCaseName: this.searchText,
          interfaceId: this.node.siaId
        }
        this.axios.get('/api/test/use/case/page', {params: params})
          .then((res) => {
            if (res.data.status === 0) {
              this.page.total = res.data.data.total;
              this.caseList = res.data.data.list;
              if (this.historyList) {
                setTimeout(() => {
                  this.caseList.forEach(item => {
                    this.historyList.forEach(child => {
                      if (item.id === child.id) {
                        this.setRow(item);
                      }
                    });
                  });
                }, 100);
              }
            }
          })
      },
      /**添加行**/
      setRow(row){
        this.$refs.multipleTable.toggleRowSelection(row,true);
        console.log(this.multipleSelection);
      },
      /**单条删除**/
      oneDelete(data) {
        this.multipleSelection = [];
        this.multipleSelection.push(data)
        this.deleteDate()
      },
      /**单击行**/
      rowClick(data) {
        if (this.isChange) {
          this.$confirm('检查到没有保存，是否继续?', '离开提示', {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning'
          }).then(() => {
            this.isChange = false;
            this.$refs['form'].resetFields();
            this.axios.get('/api/test/use/case/' + data.id)
              .then((res) => {
                this.node.updateInterfaceJson = JSON.parse(res.data.data.inBody);
                this.node.updateParamsJson = {
                  inHeader: JSON.parse(res.data.data.inHeader),
                  inQuery: JSON.parse(res.data.data.inQuery)
                };
                this.node.updateAssertJson = res.data.data.assertConditions;
                this.isNode = false;
                this.$nextTick(() => {
                  this.isNode = true;
                  this.disabled = true;
                })
                this.form = {
                  useCaseName: res.data.data.useCaseName,
                  remark: res.data.data.remark
                }
              })
          }).catch(() => {});
        }


        else {
          this.$refs['form'].resetFields();
          this.axios.get('/api/test/use/case/' + data.id)
            .then((res) => {
              this.node.updateInterfaceJson = JSON.parse(res.data.data.inBody);
              this.node.updateParamsJson = {
                inHeader: JSON.parse(res.data.data.inHeader),
                inQuery: JSON.parse(res.data.data.inQuery)
              };
              this.node.updateAssertJson = res.data.data.assertConditions;
              this.isNode = false;
              this.$nextTick(() => {
                this.isNode = true;
                this.disabled = true;
              })
              this.form = {
                useCaseName: res.data.data.useCaseName,
                remark: res.data.data.remark
              }
            })
        }


      },
      //批量删除
      deleteDate() {
        if (this.multipleSelection.length === 0) {
          this.$message({message: '请选择删除项', type: 'warning'});
          return;
        }
        this.$confirm('您确定删除该用例吗?', '温馨提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          let ids = []
          this.multipleSelection.forEach((item) => {
            ids.push(item.id)
          })
          this.axios.delete('/api/test/use/case/delete', {data: ids})
            .then((res) => {
              if (res.data.status == 0) {
                this.onloadeList()
                this.$message({message: '删除成功', type: 'success'});
                this.form = {
                  useCaseName: "",
                  remark: ""
                }
                this.multipleSelection = [];
              }
            })
        })
      },
      //点击修改，查询数据详情
      update(data) {
        this.disabled = false;
        this.isAdd = false;
        this.axios.get('/api/test/use/case/' + data.id)
          .then((res) => {
            this.node.updateInterfaceJson = JSON.parse(res.data.data.inBody);
            this.node.updateParamsJson = {
              inHeader: JSON.parse(res.data.data.inHeader),
              inQuery: JSON.parse(res.data.data.inQuery)
            };
            this.node.updateAssertJson = res.data.data.assertConditions;
            this.isNode = false;
            this.$nextTick(() => {
              this.isNode = true;
            })
            this.id = res.data.data.id
            if (res.data.status == 0) {
              let resData = res.data.data
              this.form = {
                useCaseName: resData.useCaseName,
                remark: resData.remark
              }
            }
          })
      },
      //获取数据
      getData(){
        //1.获取inHeader、inQuery
        let paramsJson = this.$refs.interfaceConfig.getParamsJson();
        //2.获取inBody
        let interfaceJson = this.$refs.interfaceConfig.getInterfaceJson();
        //3.获取断言 条件
        let assert = this.$refs.interfaceConfig.getAssert();
        let data = {
          interfaceId: this.node.siaId,
          inHeader: JSON.stringify(paramsJson.inHeader),
          inQuery: JSON.stringify(paramsJson.inQuery),
          inBody: JSON.stringify(interfaceJson),
          interfaceName: this.node.siaName,
          requestMethod: this.node.siaHttpMethod,
          requestUrl: this.node.siIpAddress + ":" + this.node.siPort + this.node.siaPath,
          useCaseName: this.form.useCaseName,
          remark: this.form.remark,
          assertConditions: [
            {
              conditions: JSON.stringify(assert)
            }
          ]
        }
        return data
      },
      //集成测试引用
      use() {
        if(this.multipleSelection.length === 0) {
          this.$message({message: '请选择引用项', type: 'warning'});
          return;
        }

        let data = {};
        data.id = this.node.siaId;
        data.useList = this.multipleSelection;
        this.$emit('useListCall', data);
      },
      //新增
      add() {
        this.$refs['form'].validate((valid) => {
          if (valid) {
            let data = this.getData()
            this.axios.post('/api/test/use/case/add', data)
              .then((res) => {
                if (res.data.status === 0) {
                  this.disabled = true;
                  this.$message({message: '新增成功', type: 'success'});
                  this.isChange = false;
                  this.onloadeList()
                }
              })

          }
        });

      },
      //关闭弹窗
      closeTask() {
        if (this.isChange) {
          this.$confirm('检查到没有保存，是否继续?', '离开提示', {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning'
          }).then(() => {
            this.isChange = false;
            this.$refs['form'].resetFields();
            this.$emit('closeCaseCall');
          }).catch(() => {});
        }
        else
          this.$emit('closeCaseCall');
      },
      //选中项
      handleSelectionChange(val) {
        this.multipleSelection = val;
      },
      //每页显示条数
      handleSizeChange(val) {
        this.page.pageSize = val
        this.onloadeList()
      },
      //当前页
      handleCurrentChange(val) {
        this.page.pageNum = val
        this.onloadeList()
      }
    }
  }
</script>

<style scoped lang="less">
  .title {
    font-size: 14px;
    font-weight: 900;
  }

  .cf:after {
    clear: both;
    content: '';
    display: table;
  }

  .search {
    margin: 10px 0;
  }
  .table{
    height: calc(100% - 110px);
    overflow-y: auto;
  }

  .caoz {
    margin-right: 10px;
    cursor: pointer;
  }

  .api_info {
    margin: 20px 0px;
    color: #999999;
  }

  .api_info span {
    color: #333333;
    margin-left: 30px;
  }

  .meg_title {
    display: inline-block;
    width: 80px;
    text-align: right
  }

  .api_info .valuetest {
    margin-left: 15px
  }

  .seccessCol {
    color: #67C23A !important;
  }

  .errorCol {
    color: #F56C6C !important;
  }

  .footer-btn {
    position: absolute;
    bottom: 10px;
    right: 20px;
  }
  .dialog-footer{
    position: absolute;
    bottom: 10px;
  }
  .flex {
    display: flex;
    height: 800px;
    .left {
      width: 400px;
      height: 100%;
      padding-right: 8px;
      box-sizing: border-box;
      .left-div{
        height: 100%;
        padding:10px 15px;
        border-right: 5px solid #e1e1e1;
        box-sizing: border-box;
      }
    }
  }
  .right {
    width: calc(100% - 360px);
    height: calc(100% - 58px);
    overflow-y: auto;
    padding: 10px 10px 0 10px;
  }
</style>

